<template>
  <view class="container">
    <uni-forms ref="form" :model="formData" :rules="rules" label-width="100rpx">
      <!-- 头像上传 -->
      <uni-forms-item label="头像" name="avatar">
        <view class="avatar-upload" @click="chooseAvatar">
          <image class="avatar" :src="formData.avatar?getBaseUrl+formData.avatar : '/static/mine1.png'"></image>
          <uni-icons class="camera-icon" type="camera-filled" size="24" color="#666"></uni-icons>
        </view>
      </uni-forms-item>

      <!-- 用户昵称 -->
      <uni-forms-item label="用户昵称" name="nickName">
        <uni-easyinput v-model="formData.nickName" placeholder="请输入昵称" />
      </uni-forms-item>

      <!-- 用户性别 -->
      <uni-forms-item label="性别" name="sex">
        <radio-group @change="onSexChange">
          <label class="radio-label">
            <radio value="0" :checked="formData.sex === '0'" /> 男
          </label>
          <label class="radio-label">
            <radio value="1" :checked="formData.sex === '1'" /> 女
          </label>
        </radio-group>
      </uni-forms-item>

      <!-- 邮箱 -->
      <uni-forms-item label="邮箱" name="email">
        <uni-easyinput v-model="formData.email" placeholder="请输入邮箱" />
      </uni-forms-item>
    <!-- 专业 -->
      <uni-forms-item label="专业" name="major">
        <uni-easyinput v-model="formData.major" placeholder="请输入专业" />
      </uni-forms-item>
	  <!-- 专业 -->
	    <uni-forms-item label="年级" name="grade">
	      <uni-easyinput v-model="formData.grade" placeholder="请输入年级" />
	    </uni-forms-item>
      <!-- 手机号 -->
     <!-- <uni-forms-item label="手机号" name="phonenumber">
        <uni-easyinput v-model="formData.phonenumber" placeholder="请输入手机号" />
      </uni-forms-item> -->

      <!-- 提交按钮 -->
      <button type="primary" @click="submitForm" class="submit-btn">保存修改</button>
    </uni-forms>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { http } from '../../../utils/requestUtil';
import getBaseUrl from '../../../utils/baseUrl.js'
const form = ref(null)
const formData = ref({
  userId: '',
  nickName: '',
  sex: '0',
  email: '',
  phonenumber: '',
  avatar: '',
  grade:'',
  major:''
})

// 表单验证规则
const rules = ref({
  nickName: {
    rules: [{
      required: true,
      errorMessage: '昵称不能为空'
    }]
  },
  email: {
    rules: [{
      format: 'email',
      errorMessage: '邮箱格式不正确'
    }]
  },
  phonenumber: {
    rules: [{
      pattern: /^1[3-9]\d{9}$/,
      errorMessage: '手机号格式不正确'
    }]
  }
})

// 初始化加载用户数据
onMounted(() => {
  const userInfo = uni.getStorageSync('userInfo')
  if (userInfo) {
    formData.value = {
      userId: userInfo.userId,
      nickName: userInfo.nickName,
      sex: userInfo.sex || '0',
      email: userInfo.email,
      phonenumber: userInfo.phonenumber,
      avatar: userInfo.avatar,
	  major:userInfo.major,
	  grade:userInfo.grade
    }
  }
})

// 选择头像
const chooseAvatar = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
	   extension: ['jpg', 'png'] // 限制文件类型
    })
    console.log(res.tempFilePaths[0])
    // 上传头像
    const uploadRes = await http.upload(
      '/common/upload',
      res.tempFilePaths[0]
    )
    console.log(uploadRes)
	if(uploadRes.code == 500){
		uni.showToast({
			title:uploadRes.msg, icon: 'none'
		})
	}else if(uploadRes.message == '上传失败: 413'){
		uni.showToast({
			title:'文件过大', icon: 'none'
		})
	}else if(uploadRes.code==200){
		uni.showToast({
			title:'图片修改'
		})
	}
    // const fileInfo = JSON.parse(uploadRes[1].data)
    formData.value.avatar = uploadRes.fileName
  } catch (err) {
	  console.log(err)
    uni.showToast({ title: '图片格式不符(请选择jpg、png图片)', icon: 'none' })
  }
}

// 性别选择
const onSexChange = (e) => {
  formData.value.sex = e.detail.value
}

// 提交表单
const submitForm = async () => {
  try {
    // 表单验证
    await form.value.validate()
    
    // 调用若依更新接口
    const res = await http.put('/system/user/profile', formData.value)
    console.log(formData.value.avatar)
    if (res.code === 200) {
      // 更新本地存储
      const userInfo = uni.getStorageSync('userInfo')
      const newInfo = { ...userInfo, ...formData.value }
      uni.setStorageSync('userInfo', newInfo)
      uni.$emit('refreshInfoData', { refresh: true });
      uni.showToast({ title: '修改成功' })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  } catch (err) {
    uni.showToast({ 
      title: err,
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.container {
  padding: 30rpx;
}

.avatar-upload {
  position: relative;
  width: 120rpx;
  height: 120rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
}

.camera-icon {
  position: absolute;
  right: -10rpx;
  bottom: -10rpx;
  background: #fff;
  border-radius: 50%;
  padding: 5rpx;
}

.radio-label {
  margin-right: 40rpx;
}

.submit-btn {
  margin-top: 40rpx;
}
</style>